# -*- coding: utf-8 -*-
"""
配置工具模块
提供配置获取和管理功能
"""

import os
from typing import Dict, Any, Optional
from pathlib import Path


def get_config(config_name: Optional[str] = None) -> Dict[str, Any]:
    """
    获取配置信息
    
    Args:
        config_name: 配置名称，可选
        
    Returns:
        Dict[str, Any]: 配置字典
    """
    # 基础配置
    base_config = {
        "api_base_url": os.getenv("API_BASE_URL", "http://localhost:8000"),
        "timeout": int(os.getenv("REQUEST_TIMEOUT", "30")),
        "retry_count": int(os.getenv("RETRY_COUNT", "3")),
        "debug": os.getenv("DEBUG", "true").lower() == "true",
        "log_level": os.getenv("LOG_LEVEL", "INFO"),
        "test_data_dir": os.getenv("TEST_DATA_DIR", "tests/data"),
        "allure_results_dir": os.getenv("ALLURE_RESULTS_DIR", "allure-results"),
        "allure_report_dir": os.getenv("ALLURE_REPORT_DIR", "allure-report"),
    }
    
    # 测试环境配置
    test_config = {
        "local": {
            "api_base_url": "http://localhost:8000",
            "database_url": "sqlite:///./test.db",
            "description": "本地开发环境"
        },
        "staging": {
            "api_base_url": "https://staging-api.example.com",
            "database_url": "postgresql://user:pass@staging-db:5432/testdb",
            "description": "预发布环境"
        },
        "production": {
            "api_base_url": "https://api.example.com",
            "database_url": "postgresql://user:pass@prod-db:5432/proddb",
            "description": "生产环境"
        }
    }
    
    # 合并配置
    config = {**base_config}
    
    # 获取当前环境
    current_env = os.getenv("TEST_ENV", "local")
    if current_env in test_config:
        config.update(test_config[current_env])
    
    # 如果指定了配置名称，返回特定配置
    if config_name:
        return config.get(config_name, {})
    
    return config


def get_test_config() -> Dict[str, Any]:
    """
    获取测试专用配置
    
    Returns:
        Dict[str, Any]: 测试配置字典
    """
    return {
        "test_timeout": int(os.getenv("TEST_TIMEOUT", "60")),
        "max_retries": int(os.getenv("MAX_RETRIES", "3")),
        "parallel_workers": int(os.getenv("PARALLEL_WORKERS", "4")),
        "cleanup_after_test": os.getenv("CLEANUP_AFTER_TEST", "true").lower() == "true",
        "generate_allure_report": os.getenv("GENERATE_ALLURE_REPORT", "true").lower() == "true",
        "capture_screenshots": os.getenv("CAPTURE_SCREENSHOTS", "false").lower() == "true",
        "verbose_logging": os.getenv("VERBOSE_LOGGING", "false").lower() == "true",
    }


def get_performance_config() -> Dict[str, Any]:
    """
    获取性能测试配置
    
    Returns:
        Dict[str, Any]: 性能测试配置字典
    """
    return {
        "default_users": int(os.getenv("PERF_DEFAULT_USERS", "10")),
        "max_users": int(os.getenv("PERF_MAX_USERS", "100")),
        "spawn_rate": int(os.getenv("PERF_SPAWN_RATE", "2")),
        "run_time": os.getenv("PERF_RUN_TIME", "60s"),
        "host": os.getenv("PERF_HOST", "http://localhost:8000"),
        "results_dir": os.getenv("PERF_RESULTS_DIR", "tests/performance/results"),
        "reports_dir": os.getenv("PERF_REPORTS_DIR", "tests/performance/reports"),
    }


def update_config(key: str, value: Any) -> None:
    """
    更新环境变量配置
    
    Args:
        key: 配置键
        value: 配置值
    """
    os.environ[key] = str(value)


def load_env_file(env_file: str = ".env") -> None:
    """
    加载环境变量文件
    
    Args:
        env_file: 环境变量文件路径
    """
    env_path = Path(env_file)
    if env_path.exists():
        with open(env_path, 'r', encoding='utf-8') as f:
            for line in f:
                line = line.strip()
                if line and not line.startswith('#') and '=' in line:
                    key, value = line.split('=', 1)
                    os.environ.setdefault(key.strip(), value.strip())